/**
 * Cloud Map Service - 与UniCloud交互的地图数据服务
 */

// 引入存储服务
import * as storageServiceModule from "./storageService";

// 轨迹管理
export const saveTrackData = async (trackData) => {
  try {
    // 调用云函数保存轨迹数据
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "saveTrack",
        data: trackData,
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data.id;
    } else {
      console.error("保存轨迹失败:", result.result.message);
      // 如果云端保存失败，回退到本地存储
      return storageServiceModule.saveTrackData(trackData);
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return storageServiceModule.saveTrackData(trackData);
  }
};

export const getTrackList = async (page = 1, pageSize = 10) => {
  try {
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "getTrackList",
        data: { page, pageSize },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data;
    } else {
      console.error("获取轨迹列表失败:", result.result.message);
      // 如果云端获取失败，回退到本地存储
      return {
        list: storageServiceModule.getSavedTracks(),
        pagination: {
          page,
          pageSize,
          total: storageServiceModule.getSavedTracks().length,
        },
      };
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return {
      list: storageServiceModule.getSavedTracks(),
      pagination: {
        page,
        pageSize,
        total: storageServiceModule.getSavedTracks().length,
      },
    };
  }
};

export const getTrackDetail = async (trackId) => {
  try {
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "getTrackDetail",
        data: { trackId },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data;
    } else {
      console.error("获取轨迹详情失败:", result.result.message);
      // 如果云端获取失败，回退到本地存储
      return storageServiceModule.getTrackById(trackId);
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return storageServiceModule.getTrackById(trackId);
  }
};

export const updateTrack = async (trackId, updateData) => {
  try {
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "updateTrack",
        data: { trackId, ...updateData },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return true;
    } else {
      console.error("更新轨迹失败:", result.result.message);
      // 如果云端更新失败，回退到本地存储
      return storageServiceModule.updateTrack(trackId, updateData);
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return storageServiceModule.updateTrack(trackId, updateData);
  }
};

export const deleteTrack = async (trackId) => {
  try {
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "deleteTrack",
        data: { trackId },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return true;
    } else {
      console.error("删除轨迹失败:", result.result.message);
      // 如果云端删除失败，回退到本地存储
      storageServiceModule.deleteTrack(trackId);
      return true;
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    storageServiceModule.deleteTrack(trackId);
    return true;
  }
};

export const getStatistics = async (type = "week") => {
  try {
    const result = await uniCloud.callFunction({
      name: "track-management",
      data: {
        action: "getStatistics",
        data: { type },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data;
    } else {
      console.error("获取统计数据失败:", result.result.message);
      // 如果云端获取失败，返回空数据
      return {
        total_distance: 0,
        total_duration: 0,
        total_calories: 0,
        count: 0,
        avg_speed: 0,
      };
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，返回空数据
    return {
      total_distance: 0,
      total_duration: 0,
      total_calories: 0,
      count: 0,
      avg_speed: 0,
    };
  }
};

// 离线地图管理
export const saveOfflineMap = async (mapData) => {
  try {
    const result = await uniCloud.callFunction({
      name: "offline-map-management",
      data: {
        action: "saveOfflineArea",
        data: {
          name: mapData.name,
          center_latitude: mapData.latitude,
          center_longitude: mapData.longitude,
          scale: mapData.scale,
          size: mapData.size || 0,
        },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data.id;
    } else {
      console.error("保存离线地图失败:", result.result.message);
      // 如果云端保存失败，回退到本地存储
      return storageServiceModule.saveOfflineMap(mapData);
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return storageServiceModule.saveOfflineMap(mapData);
  }
};

export const getOfflineMapList = async (page = 1, pageSize = 20) => {
  try {
    const result = await uniCloud.callFunction({
      name: "offline-map-management",
      data: {
        action: "getOfflineAreaList",
        data: { page, pageSize },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      // 格式转换，适配前端
      const maps = result.result.data.list.map((item) => ({
        id: item._id,
        name: item.name,
        latitude: item.center_latitude,
        longitude: item.center_longitude,
        scale: item.scale,
        size: item.size,
        date: item.create_date,
      }));

      return {
        list: maps,
        pagination: result.result.data.pagination,
      };
    } else {
      console.error("获取离线地图列表失败:", result.result.message);
      // 如果云端获取失败，回退到本地存储
      return {
        list: storageServiceModule.getOfflineMaps(),
        pagination: {
          page,
          pageSize,
          total: storageServiceModule.getOfflineMaps().length,
        },
      };
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    return {
      list: storageServiceModule.getOfflineMaps(),
      pagination: {
        page,
        pageSize,
        total: storageServiceModule.getOfflineMaps().length,
      },
    };
  }
};

export const deleteOfflineMap = async (mapId) => {
  try {
    const result = await uniCloud.callFunction({
      name: "offline-map-management",
      data: {
        action: "deleteOfflineArea",
        data: { areaId: mapId },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return true;
    } else {
      console.error("删除离线地图失败:", result.result.message);
      // 如果云端删除失败，回退到本地存储
      storageServiceModule.deleteOfflineMap(mapId);
      return true;
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    // 如果调用云函数失败，回退到本地存储
    storageServiceModule.deleteOfflineMap(mapId);
    return true;
  }
};

// 网络状态监控
export const isOnline = () => {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        // 如果网络类型为none，则表示离线
        resolve(res.networkType !== "none");
      },
      fail: () => {
        // 获取失败时默认为离线
        resolve(false);
      },
    });
  });
};

// 同步本地数据到云端
export const syncLocalDataToCloud = async () => {
  try {
    // 获取本地保存的所有轨迹
    const localTracks = storageServiceModule.getSavedTracks();

    if (!localTracks || localTracks.length === 0) {
      return { success: true, message: "没有需要同步的数据" };
    }

    let syncedCount = 0;
    let failedCount = 0;

    // 获取在线状态
    const online = await isOnline();
    if (!online) {
      return { success: false, message: "当前处于离线状态，无法同步数据" };
    }

    // 遍历本地轨迹，同步到云端
    for (const track of localTracks) {
      // 如果轨迹ID已经是云端格式（例如使用了_id），则跳过
      if (track._id) continue;

      // 调用云函数保存轨迹
      try {
        const result = await uniCloud.callFunction({
          name: "track-management",
          data: {
            action: "saveTrack",
            data: track,
            uniIdToken: uni.getStorageSync("uni_id_token"),
          },
        });

        if (result.result.code === 0) {
          // 同步成功，可以从本地删除该轨迹
          storageServiceModule.deleteTrack(track.id);
          syncedCount++;
        } else {
          failedCount++;
        }
      } catch (e) {
        failedCount++;
        console.error("同步轨迹失败:", e);
      }
    }

    return {
      success: true,
      message: `同步完成，成功${syncedCount}条，失败${failedCount}条`,
    };
  } catch (e) {
    console.error("数据同步出错:", e);
    return { success: false, message: "数据同步过程中出现错误" };
  }
};

// 附近同伴管理
export const updateLocation = async (latitude, longitude) => {
  try {
    const result = await uniCloud.callFunction({
      name: "nearby-friends",
      data: {
        action: "updateLocation",
        data: { latitude, longitude },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    return result.result.code === 0;
  } catch (e) {
    console.error("更新位置失败:", e);
    return false;
  }
};

export const getNearbyFriends = async (
  latitude,
  longitude,
  distance = 5000
) => {
  try {
    const result = await uniCloud.callFunction({
      name: "nearby-friends",
      data: {
        action: "getNearbyFriends",
        data: { latitude, longitude, distance },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    if (result.result.code === 0) {
      return result.result.data;
    } else {
      console.error("获取附近同伴失败:", result.result.message);
      return [];
    }
  } catch (e) {
    console.error("调用云函数失败:", e);
    return [];
  }
};

export const setStatus = async (status) => {
  try {
    const result = await uniCloud.callFunction({
      name: "nearby-friends",
      data: {
        action: "setStatus",
        data: { status },
        uniIdToken: uni.getStorageSync("uni_id_token"),
      },
    });

    return result.result.code === 0;
  } catch (e) {
    console.error("设置状态失败:", e);
    return false;
  }
};
